package handler

import (
	"github.com/gin-gonic/gin"
	"log"
	"path/filepath"
	"time"
	"yuekao3/dao"
	"yuekao3/global"
	"yuekao3/model"
	"yuekao3/pkg"
	"yuekao3/pkg/jwt"
	"yuekao3/request"
	"yuekao3/response"
)

const JWT_USER_ID = "2210A"

func Login(c *gin.Context) {
	var data request.LoginUser
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Name: data.Name}, &user)
	if user.Id == 0 {
		response.ResponseError(c, "用户不存在", nil)
		return
	}
	if user.Password != data.Password {
		response.ResponseError(c, "密码错误", nil)
		return
	}
	claims := jwt.CustomClaims{ID: user.Id}
	token, err := jwt.NewJWT(JWT_USER_ID).CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "token生成失败", nil)
		return
	}
	response.ResponseSuccess(c, "登陆成功", token)
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	name := filepath.Ext(file.Filename)
	name1 := time.Now().Format("20060102150405") + name
	dst := "D:\\gocode\\src\\gao3\\2\\rk\\3\\19\\yuekao3\\stonic\\upload\\" + file.Filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)
	pkg.Oss(dst, name1)
	filename := pkg.OssFileName(name1)
	response.ResponseSuccess(c, "上传成功", filename)
	//	c.String(http.StatusOK, fmt.Sprintf(filename))
}

func VideoTable(c *gin.Context) {
	var video []model.VideoTable
	dao.Losts(&video)
	response.ResponseSuccess(c, "列表展示成功", video)

}

func SearchVideoTable(c *gin.Context) {
	var data request.SearchVideoTable
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	var video model.VideoTable
	dao.GetOneByField(data.Name, &video)
	response.ResponseSuccess(c, "搜索成功", video)

}

func Add(c *gin.Context) {
	var data request.Add
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	a := pkg.BaiDu(data.Name)
	log.Println(a)

	dan := model.Danmu{
		Content: data.Name,
	}
	// 开始事务
	tx := global.DB.Begin()

	// 在事务中执行一些 db 操作（从这里开始，您应该使用 'tx' 而不是 'db'）
	if a == false {
		response.ResponseError(c, "不合规", "不合规")
		// 遇到错误时回滚事务
		tx.Rollback()

		return
	}
	// ...

	dao.Create(&dan)
	// 否则，提交事务
	tx.Commit()

	response.ResponseSuccess(c, "合规", nil)
}
